package com.pw.study.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author: linux_future
 * @since: 2022/3/30
 **/
public abstract class BaseServer {

    public static Socket webApp=null;

    public void init(int serverPort) throws IOException {
        System.out.println("server init .... ");
        ServerSocket server = new ServerSocket(serverPort);
        System.out.println("server running .....");
        for (; ; ) {
            Socket data = server.accept();
            if (data.getPort() == 8888) {
                //后台客户端
                webApp = data;
            } else {
            //请求客户端
                System.out.println("client address:" + data.getRemoteSocketAddress());
                new Thread(() -> {
                    try (InputStream in = data.getInputStream()) {
                        try (OutputStream out = data.getOutputStream()) {
                            msgHandler(in, out);
                        }
                    } catch (IOException e) {
                        try {
                            data.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                        System.out.println("client disconnected ...");
                    }
                }).start();

            }
        }

    }

    protected abstract void msgHandler(InputStream in, OutputStream out) throws IOException;
}



